//
//  YZLCarRedioPlayer.m
//  Car
//
//  Created by dllo on 15/11/5.
//  Copyright © 2015年 岳明. All rights reserved.
//

#import "YZLCarRedioPlayer.h"

@implementation YZLCarRedioPlayer

//创建播放器单例
+ (YZLCarRedioPlayer *)shareInstance {
    
    static YZLCarRedioPlayer *redioPlayer = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        
        redioPlayer = [[YZLCarRedioPlayer alloc] init];
    });
     
    return redioPlayer;
}

//- (AVPlayer *)player
//{
//    if (!_player) {
//
//        self.player = [AVPlayer new];
//
//    }
//    return _player;
//}

- (void)prepareToPlayWithStr:(NSString *)fileStr {
    
    if (!fileStr) {
        return;
    }
    if (![self.currentStr isEqualToString:fileStr]) {
        
        [self pause];
        
        NSLog(@"%@", fileStr);
        self.player = [AVPlayer new];
        NSURL *url = [NSURL URLWithString:fileStr];
        self.playItem = [[AVPlayerItem alloc] initWithURL:url];
        NSLog(@"~~%@", self.playItem);
        //准备播放
        [self.player replaceCurrentItemWithPlayerItem:self.playItem];
        self.currentStr = fileStr;
        
    }else {
        
        [self.time invalidate];
        self.time = nil;
    }
    
}

//播放过程中，一直执行此方法
//sender 定时器
- (void)playingAction:(NSTimer *)sender
{
    // 不断执行代理方法
    if (self.delegate && [self.delegate respondsToSelector:@selector(AVPlayingWithProgress:)]) {
        
        //  value/timescale = seconds  总值/时间刻度
        float progress = 1.0 * self.player.currentTime.value / self.player.currentTime.timescale;
        
        [self.delegate AVPlayingWithProgress:progress];
    }
}

//播放
- (void)play {
    
    [self.player play];
    
    self.time = [NSTimer scheduledTimerWithTimeInterval:.1 target:self selector:@selector(playingAction:) userInfo:nil repeats:YES];
    
    //将定时器加入到NSRunLoop模式中
    [[NSRunLoop currentRunLoop] addTimer:self.time forMode:NSRunLoopCommonModes];
}

//暂停
- (void)pause {
    
    [self.player pause];
    
    [self.time invalidate];
    self.time = nil;
}

@end
